package com.avantis.common.utils;

import com.avantis.common.entity.SysSerialNumber;
import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;

/**
 * @Author: tracywang
 * @Date: 2019/1/28
 * @Descrption:
 */
public class NumberGenerater {

    private static final String TIME_FORMATER = "yyyyMMddHHmmss"; 		//时间格式

    private static final String SERIAL_NUMBER = "XXXXXXXXXXX";		//流水号格式

    private static final String pattern = TIME_FORMATER+"-"+SERIAL_NUMBER; //编码格式

    private static final String SERIAL_CHAR="X";

    private  static NumberGenerater numberGenerater	=	null;

    private NumberGenerater(){

    }



    /**

     * 取得NumberGenerater的单例实现

     * @return

     */

    public static NumberGenerater getInstance(){

        if(numberGenerater==null){

            synchronized(NumberGenerater.class){

                if(numberGenerater==null){

                    numberGenerater = new NumberGenerater();

                }

            };

        }

        return numberGenerater;

    }

    /**

     * 生成编号

     * @param sysSerialNumber

     * @return

     */

    public synchronized String generaterNextNumber(String sno){


        //取得序列号格式化字符串

        int count =SERIAL_NUMBER.length();

        StringBuilder sb = new StringBuilder();

        for(int i=0;i<count;i++){

            sb.append("0");

        }
        int currentSerial = 0;
        DecimalFormat df = new DecimalFormat(sb.toString());
            if(StringUtils.isEmpty(sno)) {
                currentSerial = 1;
            }else{
                currentSerial =1 + Integer.parseInt(sno.substring(8, 12));
            }

            //当前的流水号

            String currentSerialNumber = df.format(currentSerial);

            StringBuilder subSb = new StringBuilder();

            String currentNumber = subSb.append(sno.substring(0,8))
                    .append(DateUtils.getCurrentDate(DateUtils.DEFAULT_DARE_FORMAT_GENERATE))
                    .append(currentSerialNumber).toString();

            return currentNumber;

    }

    /**
     * 生成条形码
     * @param type
     * @return
     */
    public synchronized String generaterBarCode(String type){


        //取得序列号格式化字符串

        int count =SERIAL_NUMBER.length();

        StringBuilder sb = new StringBuilder();

        for(int i=0;i<count;i++){

            sb.append("0");

        }

        java.text.DecimalFormat df = new java.text.DecimalFormat(sb.toString());

        int currentSerial =1 ;

        //当前的流水号

        String currentSerialNumber = df.format(currentSerial);

        StringBuilder subSb = new StringBuilder();

        String currentNumber = subSb.append(type)
                .append("-")
                .append(DateUtils.getCurrentDate(DateUtils.DEFAULT_DARE_FORMAT_GENERATE))
                .append("-")
                .append(currentSerialNumber).toString();

        return currentNumber;

    }
}
